﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace QLTuyenXe.DAL
{
    class MyConnect
    {
        String server;
        String database;
        String username;
        String password;
        SqlConnection conn;
        //Khởi tạo đối tượng kết nối CSDL
        public MyConnect(String server, String database, String username, String password)
        {
            this.server = server;
            this.database = database;
            this.username = username;
            this.password = password;
            String sqlString = "DATA SOURCE=" + server + ";INITIAL CATALOG="
                 + database + "; USER ID =" + username + "; PASSWORD=" + password;
            conn = new SqlConnection(sqlString);
        }
        //Đọc dữ liệu từ CSDL
        public DataTable Read(String query)
        {
            //System.Windows.Forms.MessageBox.Show (query.ToString());
            SqlCommand cmd = new SqlCommand(query, conn);
            try
            {
                conn.Open();
                SqlDataReader drd = cmd.ExecuteReader();
                DataTable tb = new DataTable();
                tb.Load(drd, LoadOption.OverwriteChanges);
                conn.Close();
                return tb;
            }
            catch
            {
                return null;
            }
        }

        //Thêm/Sửa/Xóa dữ liệu
        public int Write(String query)
        {           
            SqlCommand cmd = new SqlCommand(query, conn);
            //System.Windows.Forms.MessageBox.Show (query.ToString());
            try
            {
                if(conn.State == ConnectionState.Closed)
                    conn.Open();
                int result = cmd.ExecuteNonQuery();
                conn.Close();
                return result;
            }
            catch(SqlException e1)
                //catch
            {
                System.Windows.Forms.MessageBox.Show(e1.ToString());
                //return -1;
                //System.Windows.Forms.MessageBox.Show("Nhóm này chưa được phép xóa");
                return -1;
            }
        }
    }
}
